package LeetCode.month02.day33;

import java.util.Arrays;

public class No3413 {
    public static void main(String[] args) {
        System.out.println(maximumCoins(new int[][]{{1,10,3}},2));
    }
    public static long maximumCoins(int[][] coins, int k) {
        Arrays.sort(coins,(a,b)->a[0]-b[0]);
        long ans = maximum(coins,k);
        for (int i = 0,j = coins.length-1; i < j; i++,j--) {
            int[] temp = coins[i];
            coins[i]=coins[j];
            coins[j] =temp;
        }
        for (int[] coin : coins) {
            int temp = coin[0];
            coin[0] = -coin[1];
            coin[1] = -temp;
        }
        return Math.max(ans,maximum(coins,k));
    }

    private static long maximum(int[][] coins, int k) {
        int left =0;
        long res = 0;
        long sum = 0;
        for (int right = 0; right < coins.length; right++) {
            sum+=(long)(coins[right][1]-coins[right][0]+1)*coins[right][2];
            while(coins[right][1]-k+1>coins[left][1]){
                sum-=(long)(coins[left][1]-coins[left][0]+1)*coins[left][2];
                left++;
            }
            long uncover = Math.max(0,(long)(coins[right][1]+1-k-coins[left][0])*coins[left][2]);
            res = Math.max(res,sum-uncover);
        }
        return res;
    }
}
/*

 */
